package com.sinosoft.ci.patch.svn;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.tmatesoft.svn.core.SVNException;

import com.sinosoft.ci.utils.EasySvnClient;

/**
 * 从 svn 解析出修改的文件
 * 
 * @author 韩朝祥
 *
 */
public class SvnModifiedEntryExtractor {
	private static final Logger logger = Logger.getLogger(SvnModifiedEntryExtractor.class);
	
	private EasySvnClient svnClient;
	private String appSrcPath;
	
	/**
	 * 
	 * @param appSrcPath 工程代码路径
	 * @param svnurl
	 * @param username
	 * @param password
	 */
	public SvnModifiedEntryExtractor(String appSrcPath,String svnurl,String username,String password){
		svnClient = new EasySvnClient(svnurl, username, password);
		this.appSrcPath = appSrcPath;
	}
	
	/**
	 * 从特定的 svn 版本中提取出文件改动条目
	 * @param svnVersions
	 * @return
	 */
	public String[] getSvnFileChangeEntrys(long[] svnVersions){
		List<String> entrys = new ArrayList<String>();
		
		for(long version : svnVersions){
			String[] svnEntrys = null;
			try{
				svnEntrys = svnClient.getFileChangedList(version,appSrcPath);
			}catch(SVNException ex){
				logger.error("读取 SVN 日志失败！", ex);
			}
			
			if(null == svnEntrys || svnEntrys.length < 1){
				throw new RuntimeException(String.format("未能读取版本为 %s 的 svn 修改记录！", version));
			}
			
			for(String entry : svnEntrys){
				if(entry.length() < appSrcPath.length() + 1){
					continue;
				}
				String e = entry.substring(appSrcPath.length() + 1);
				if(!entrys.contains(e)){
					entrys.add(e);
				}
			}
		}
		
		return entrys.toArray(new String[entrys.size()]);
	}
}
